package com.atguigu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class FlowLimitController {
    @GetMapping("/testA")
    public String testA() {
        log.info("testA");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "testA";
    }

    @GetMapping("/testB")
    @SentinelResource(value = "testB", blockHandler = "testBee", fallback = "testBFallBack")
    public String testB() {
        log.info("testB");
        int j = 7 / 0;
        return Thread.currentThread().getName() + "testB";
    }

    public String testBee(BlockException exception) {

        return Thread.currentThread().getName() + "testB----blockHandler";
    }

    public String testBFallBack() {

        return Thread.currentThread().getName() + "testB" + "---fallback";
    }

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException", fallback = "testBFallBack")
    public String byResource() {
        int j = 7 / 0;
        return "按资源名称限流测试OK";
    }

    public String handleException(BlockException exception) {
        return exception.getClass().getCanonicalName() + "\t 服务不可用";
    }
    @GetMapping("/testC")
    @SentinelResource(value = "testC", blockHandler = "handleException2")
    public String testC(@RequestParam(value = "p1", required = false) String p1,
                        @RequestParam(value = "p2", required = false) String p2) {
        return "testC"+"p1==="+p1+",p2==="+p2;
    }

    public String handleException2(String p1,String p2,BlockException exception) {
        return exception.getClass().getCanonicalName() + "\t 热点限流服务不可用";
    }
}
